package com.blue.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class SqlSessionUtil {
    private SqlSessionUtil() {
    }

    private static SqlSessionFactory factory;

    private static final ThreadLocal<SqlSession> local = new ThreadLocal<>();

    static {
        try {
//            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//            Reader resourceAsReader = Resources.getResourceAsReader("mybatis-config.xml");
//            factory = builder.build(resourceAsReader);
            factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 SqlSession 对象
     *
     * @return 会话对象
     */
    public static SqlSession openSession() {
        SqlSession sqlSession = local.get();

        if (sqlSession == null) {
            sqlSession = factory.openSession();
            local.set(sqlSession);
        }

        return sqlSession;
    }

    public static void close(SqlSession sqlSession) {
        if (sqlSession != null) {
            local.remove();
            sqlSession.close();
        }
    }
}
